package cn.zxcoder.controller.goods;

import cn.zxcoder.entity.goods.Image;
import cn.zxcoder.entity.goods.Product;
import cn.zxcoder.entity.Res;
import cn.zxcoder.service.IImageService;
import cn.zxcoder.service.IProductService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

@Api(tags = "保存商品信息-api")
@RequestMapping("/api/Goods")
@RestController
@Slf4j
public class ProductSaveController {


    @Autowired
    IProductService productServiceImpl;

    @Resource
    RedisTemplate redisTemplate;

    @Value("${img.Url}")
    private String saveUrl;

    @Autowired
    IImageService iImageServiceIml;
    /**
     * 保存一个商品信息
     */
    @ApiOperation("保存商品信息")
    @PostMapping("/save")
    @Transactional(rollbackFor = ArithmeticException.class)
    public Res goodsSave(@RequestParam String goodsName, @RequestParam String goodsId, @RequestParam String title, @RequestParam String token, @RequestParam String goodsPrice, HttpServletRequest request) throws IOException {

        if (title.equals("添加")) {
            Product product = new Product();
            product.setGoodsName(goodsName);
            product.setGoodsPrice(goodsPrice);
            product.setEditTime(new Date());
            product.setEditUser(token);

            boolean save = productServiceImpl.save(product);
            //创建对应的图片文件夹
            String url = saveUrl + product.getId();
            File file = new File(url);
            boolean mkdir = file.mkdir();
            if (mkdir) {
                System.out.println("创建成功");
            }


            if (save) {
                return new Res(save, null, "保存成功");
            } else {
                return new Res(save, null, "保存失败");
            }
        } else {
            Product product = new Product();

            product.setId(Integer.parseInt(goodsId));
            product.setGoodsName(goodsName);
            product.setGoodsPrice(goodsPrice);
            product.setEditTime(new Date());
            product.setEditUser(token);

            boolean update = productServiceImpl.updateById(product);
            return new Res(update, null, "保存失败");
        }

    }


    /**
     * 保存一个商品信息
     */
    @ApiOperation("保存商品图片")
    @PostMapping("/img")
    @Transactional(rollbackFor = ArithmeticException.class)
    public Res goodsImgSave(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception {


        String id = request.getParameter("id");
        if (id == null) {//增加的情况
            List<Product> list = productServiceImpl.list();
            id = list.get(list.size() - 1).getId() + 1 + "";

        }
        if (file.isEmpty()) {
            return new Res(false, null, "上传图片失败");
        }
        //获取文件名
        String _fileName = file.getOriginalFilename();//QQ图片20220101181443.jpg
        assert _fileName != null;
        int i = _fileName.indexOf(".");
        String fileName = _fileName.substring(0, i);
        log.info("上传的文件名为:" + fileName);
        //获取文件后缀名
        String suffixName = _fileName.substring(i);
        log.info("后缀名是:" + suffixName);
        //文件上传的路径
        String imgUrl = fileName + System.currentTimeMillis() + suffixName;
        String url = saveUrl + "/" + id+"/"+imgUrl;
        System.out.println(url);
        File dest = new File(url);
        if (!dest.exists()) {
            dest.mkdir();
        }
        try {
            file.transferTo(dest);

            //放入数据库
            Image image = new Image();

            image.setImgUrl(imgUrl);
            iImageServiceIml.save(image);

            //与对应的product建立联系
            QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("id", Integer.parseInt(id));
            Product product = productServiceImpl.getById(id);
            String srcLists = product.getSrcLists() == null || product.getSrcLists().equals("")?  "":product.getSrcLists()+",";

            UpdateWrapper<Product> updateWrapper = new UpdateWrapper<>();
            if (product.getUrl() == null||product.getUrl().equals("")) {//设置对应的默认url
                updateWrapper.set("url", imgUrl);

            }
            updateWrapper.eq("id", Integer.parseInt(id));
            updateWrapper.set("srcLists", srcLists + image.getId());
            productServiceImpl.update(updateWrapper);


            return new Res(true, null, "上传图片成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Res(true, null, "上传图片有问题");

//        ServletInputStream inputStream = request.getInputStream();
//        byte[] bytes = new byte[1024];
//        int length = -1;
//        while ((length = inputStream.read(bytes)) != -1) {
//            String s = new String(bytes, 0, length);
//            System.out.println(s);
//
//        }
//        inputStream.close();


//        String imgName = img.getOriginalFilename();
//        System.out.println(imgName);
//        FileOutputStream fileOutputStream = new FileOutputStream(saveUrl+);

    }
}
